package com.david.auth.controller;

import com.david.auth.pojo.constants.AuthBiz;
import com.david.auth.pojo.api.AuthApi;
import com.david.auth.pojo.query.SignQuery;
import com.david.auth.pojo.query.TokenQuery;
import com.david.auth.pojo.result.R;
import com.david.auth.service.IAuthClientService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author David
 * @desc token获取
 * @date 2022/4/18 20:14
 */
@RestController
@RequestMapping("/auth/token/")
public class TokenController implements AuthApi {

    static Logger log = LoggerFactory.getLogger(TokenController.class);

    @Autowired
    private IAuthClientService iAuthClientService;

    @PostMapping(name = "获取token", value = "/getToken")
    @ApiOperation(value = "获取token", httpMethod = "POST")
    public R<String> getToken(@RequestBody @Validated SignQuery tokenQuery) {
        try {
            //验证客户端是否合法
            String token = iAuthClientService.getToken(tokenQuery);
            log.info("appkey{}获取token成功!", tokenQuery.getAppKey());
            return R.ok("获取token成功!",token);
        } catch (Exception e) {
            log.error("获取token失败!{}", e);
            return R.fail(AuthBiz.FAIL_GET_TOKEN);
        }
    }


    @Override
    public R<String> verifyToken(@RequestBody @Validated TokenQuery tokenQuery) {
        try {
            boolean bl = iAuthClientService.verifyToken(tokenQuery);
            log.info(bl ? "appKey{}token验证成功!" : "appKey{}token验证失败!", tokenQuery.getAppKey());
            return bl ? R.ok() : R.fail();
        } catch (Exception e) {
            log.error("token验证失败!{}", e);
            return R.fail(AuthBiz.FAIL_AUTH);
        }
    }
}
